package com.wgt.controller;

import com.alibaba.fastjson.JSONObject;
import com.wgt.domain.Authority;
import com.wgt.domain.EsBlog;
import com.wgt.domain.User;
import com.wgt.service.authority.AuthorityService;
import com.wgt.service.es.EsBlogService;
import com.wgt.service.user.UserService;
import com.wgt.vo.TagVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

/**
 * 基本路径控制
 * @author wgt
 * @date 2018/1/3
 * @project new-start-blog
 */
@Slf4j
@Controller
public class MainController {
    private static final Integer ROLE_USER_AUTHORITY_ID = 2;

    @Autowired
    private AuthorityService authorityService;

    @Autowired
    private UserService userService;

    @Autowired
    private EsBlogService esBlogService;

    @RequestMapping("/")
    public String root(){
        return "redirect:index";
    }

    @RequestMapping("/index")
    public String index(){
        log.info("####初始化主页####");
        return "redirect:/blogs";
    }

    @RequestMapping("/login")
    public String login(@RequestParam(value = "register",required = false)Boolean register,Model mode){
        log.info("####初始化登陆####");
        //判断是否从注册跳转过来
        if(register != null && register){
            mode.addAttribute("registerSuccess",true);
            mode.addAttribute("registerMsg", "恭喜你，注册成功!");
        }
        return "login";
    }

    @GetMapping("/register")
    public String register(){
        log.info("####初始化博主注册####");
        return "register";
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/register")
    public String registerUser(User user) {
        log.info("####博主注册###");
        List<Authority> authorities = new ArrayList<>();
        authorities.add(authorityService.getAuthorityById(ROLE_USER_AUTHORITY_ID));
        user.setAuthorities(authorities);
        userService.saveOrUpdateUser(user);
        log.info(">>>>>>博主[{}]注册成功。",user.getUsername());
        return "redirect:/login?register=true";
    }

    @RequestMapping("/login-error")
    public String loginError(Model mode){
        mode.addAttribute("loginError",true);
        mode.addAttribute("errorMsg", "登陆失败，用户名或密码错误");
        return "login";
    }
}
